﻿Imports System
Imports IDServer
Imports System.Threading.Thread
Imports System.IO
Imports System.String
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient

Public Class Frm_SelectSC
	Implements IDServer.IDServer.IDServer

	Public ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
	Private mDataset As DataSet
    Private FrmMain As New Frm_MainForm
    Public Fields, strFileName As String
    Private SelectNode As TreeNode
    Private selectObj As TextBox '選中的TextBox
    Private Img As ImageList
    Private GoodsDs As DataSet
    Private WithEvents MainFrom As New Frm_MainForm
    Private Captionstr As String = "代碼^fCode&中文名稱^fCName&英文名稱^fEName&企業法人^fDirector&地址^fAddress&電話^fPhone&電話一^fPhone1&傳真^fFax&傳真一^fFax1&公司站點^fWebsite&Email^fEmail&備註^fRemark"
    Private _Ds As DataSet '返回的資料集
    Private _fCode As String
    Private _Caption As String


    ''' <summary>
    ''' 獲取或設置資料集（DataSet）
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Ds() As DataSet
        Get
            Return _Ds
        End Get
        Set(ByVal value As DataSet)
            _Ds = value
        End Set
    End Property

    ''' <summary>
    ''' 獲取或設置查詢的代碼
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property fCode() As String
        Get
            Return _fCode
        End Get
        Set(ByVal value As String)
            _fCode = value
        End Set
    End Property

    ''' <summary>
    ''' 獲取或設置字元串
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property Caption() As String
        Get
            Return _Caption
        End Get
        Set(ByVal value As String)
            _Caption = value
        End Set
    End Property



	Private Sub Frm_SelectGoods_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
		Try
			If e.KeyCode = Keys.Shift Then
				e.Handled = True
				If e.KeyCode = Keys.Enter Then
					SendKeys.Send("+{TAB}")
					SendKeys.Send("{F4}")
				End If
			Else
				Select Case e.KeyCode
					Case Keys.Enter
						e.Handled = True
						SendKeys.Send("{TAB}")
				End Select
			End If
		Catch ex As Exception
            MsgBox("txtCode_KeyDown:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub Frm_SelectGoods_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Cursor = Cursors.WaitCursor

            If Me.Caption & "" <> "" Then
                Captionstr = Me.Caption
            End If

            DataBindGridView(Me.dgrdGoods, Captionstr)
            DataBindGrid(Me.dgrdGoods, Captionstr)

            FormatDataGridView(Me.dgrdGoods)
            With Me.dgrdGoods
                .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None
                .MultiSelect = PubMultiSelect
            End With

            If Me.txtfCode.Text & "" <> "" Then
                Me.BtnFind_Click(sender, e)
            End If

            '隱藏科目內碼
            If Me.radAccount.Checked Then
                Me.dgrdGoods.Columns(0).Visible = False
            End If

            Me.txtfCode.Focus()



        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub Panel1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Panel1.Paint

    End Sub

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd

    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel

    End Function

    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete

    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit

    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave

    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function


    Private Sub txtBarcode_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtfCode.KeyDown, _
                                   txtCname.KeyDown, txtEname.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        Me.BtnFind_Click(sender, e)
                    Case Keys.Escape
                        Me.btnCancel_Click(sender, e)
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub txtBarcode_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtfCode.TextChanged, txtCname.TextChanged, _
                txtEname.TextChanged
        Me.BtnFind_Click(sender, e)

    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click

        Try
            Dim Sql As String

            If Me.radSupplier.Checked = True Then
                Sql = "select Code, Cnname, Enname, Shortname," & _
                                    "Director, Linkman, CnAddress, EnAddress, Phone1  ,Phone2 ,   " & _
                                    "Fax1, Fax2, Email, Website, Country, Province,City," & _
                                    "Postcode, Payterm= c.ListA, Account, Bank, AccountName,  " & _
                                    "status=( CASE  status WHEN 1 THEN  '使用' ELSE '停用' END)  ,Currency=b.ListA   ,	" & _
                                    "Creditlimit,	Taxnum ,Taxrate  ,  " & _
                                    " Discount, Salemode, StopDate, OfficeHours1= convert(char(5),OfficeHours1,108),  " & _
                                    "OfficeHours2= convert(char(5),OfficeHours2,108),RoundNumber=CASE RoundNumber WHEN 1 THEN '是' ELSE '否' END, " & _
                                    "  Immediate=CASE Immediate WHEN 1 THEN '是' ELSE '否' END, CIQnum, ParementID, Remark" & _
                                    "  from  dbo.BSC_Supplier a " & _
                                    " left  join (select ListCode,ListA from BSC_OtherDefineB   " & _
                                    "  where ItemNo=(select ID from BSC_OtherDefineA where ItemCode='CurrencyDefine') ) b " & _
                                    "  on a.Currency=b.ListCode    " & _
                                    " left  join (select ListCode,ListA from BSC_OtherDefineB  " & _
                                    "  where ItemNo=(select ID from BSC_OtherDefineA where ItemCode='Payterm') ) c " & _
                                    " on a.Payterm=c.ListCode  where 1=1 "

                If Me.txtfCode.TextLength > 0 Then
                    Sql += " and a.Code Like '%" & Me.txtfCode.Text.Trim & "%'"
                End If

                If Me.txtCname.TextLength > 0 Then
                    Sql += " and a.CnName Like '%" & Me.txtCname.Text.Trim & "%'"
                End If

                If Me.txtEname.TextLength > 0 Then
                    Sql += " and a.EnName Like '%" & Me.txtEname.Text.Trim & "%'"
                End If

             
            ElseIf Me.radCustomer.Checked = True Then
                Sql = "select Code, Cnname, Enname, Shortname," & _
                    "Director, Linkman, CnAddress, EnAddress, Phone1  ,Phone2 ,   " & _
                    "Fax1, Fax2, Email, Website, Country, Province,City," & _
                    "Postcode, Payterm= c.ListA, Account, Bank, AccountName,  " & _
                    "status=( CASE  status WHEN 1 THEN  '使用' ELSE '停用' END)  ,Currency=b.ListA   ,	" & _
                    "Creditlimit,	Taxnum ,Taxrate  ,  " & _
                    " Discount, Salemode, StopDate, OfficeHours1= convert(char(5),OfficeHours1,108),  " & _
                    "OfficeHours2= convert(char(5),OfficeHours2,108),RoundNumber=CASE RoundNumber WHEN 1 THEN '是' ELSE '否' END, " & _
                    "  Immediate=CASE Immediate WHEN 1 THEN '是' ELSE '否' END, CIQnum, ParementID, Remark " & _
                     " from  dbo.BSC_Customer a " & _
                    " left  join (select ListCode,ListA from BSC_OtherDefineB   " & _
                    "  where ItemNo=(select ID from BSC_OtherDefineA where ItemCode='CurrencyDefine') ) b " & _
                    "  on a.Currency=b.ListCode    " & _
                    " left  join (select ListCode,ListA from BSC_OtherDefineB  " & _
                    "  where ItemNo=(select ID from BSC_OtherDefineA where ItemCode='Payterm') ) c " & _
                    " on a.Payterm=c.ListCode  where 1=1 "

                If Me.txtfCode.TextLength > 0 Then
                    Sql += " and a.Code Like '%" & Me.txtfCode.Text.Trim & "%'"
                End If

                If Me.txtCname.TextLength > 0 Then
                    Sql += " and a.CnName Like '%" & Me.txtCname.Text.Trim & "%'"
                End If

                If Me.txtEname.TextLength > 0 Then
                    Sql += " and a.EnName Like '%" & Me.txtEname.Text.Trim & "%'"
                End If

            ElseIf Me.RBtnStorHouse.Checked = True Then
                Sql = " SELECT FCODE,FSHORTNAME,FNAME,FTYPE,FEMPLOYEEID,FCITY,FPROVINCE,FCOUNTRY,FADDRESS,FPHONE,FSTATUS=CASE FSTATUS WHEN 0 THEN '未禁用' WHEN 1 THEN '已禁用' END,FSTOREPLACE=CASE FSTOREPLACE WHEN 0 THEN '否' WHEN 1 THEN '是' END,FREMARK FROM BSC_STOREHOUSE WHERE 1=1 "
                If Me.txtfCode.TextLength > 0 Then
                    Sql += " and fcode like '%" & Me.txtfCode.Text.Trim & "%'"
                End If
                If Me.txtCname.TextLength > 0 Then
                    Sql += " and FSHORTNAME Like '%" & Me.txtCname.Text.Trim & "%' "
                End If

            Else
                Sql = "SELECT   faccountid,"
                Sql = Sql & "          fnumber,"
                Sql = Sql & "          a.fname,"
                Sql = Sql & "          a.fname_cht,"
                Sql = Sql & "          fgroupid = b.fname_cht,"
                Sql = Sql & "          fdc = CASE fdc "
                Sql = Sql & "                  WHEN 1 THEN '借'"
                Sql = Sql & "                  ELSE '貸'"
                Sql = Sql & "                END,"
                Sql = Sql & "          fhelpercode,"
                Sql = Sql & "          fcurrencyid = CASE fcurrencyid "
                Sql = Sql & "                          WHEN (SELECT Isnull(fvalue,'HKD')"
                Sql = Sql & "                                FROM   dbo.[BSC_SystemProfile]"
                Sql = Sql & "                                WHERE  fcategory = 'System'"
                Sql = Sql & "                                       AND fkey = 'Standard money') THEN '(不核算)'"
                Sql = Sql & "                          ELSE (SELECT lista"
                Sql = Sql & "                                FROM   dbo.bsc_otherdefineb"
                Sql = Sql & "                                WHERE  itemno = (SELECT Top 1  id"
                Sql = Sql & "                                                 FROM   dbo.bsc_otherdefinea"
                Sql = Sql & "                                                 WHERE  itemcode = 'CurrencyDefine')"
                Sql = Sql & "                                       AND listcode = a.fcurrencyid)"
                Sql = Sql & "                        END,"
                Sql = Sql & "          fadjustrate = CASE fadjustrate "
                Sql = Sql & "                          WHEN 1 THEN '是'"
                Sql = Sql & "                          ELSE '否'"
                Sql = Sql & "                        END,"
                Sql = Sql & "          fquantities = CASE fquantities "
                Sql = Sql & "                          WHEN 1 THEN '是'"
                Sql = Sql & "                          ELSE '否'"
                Sql = Sql & "                        END,"
                Sql = Sql & "          fiscash = CASE fiscash "
                Sql = Sql & "                      WHEN 1 THEN '是'"
                Sql = Sql & "                      ELSE '否'"
                Sql = Sql & "                    END,"
                Sql = Sql & "          fisbank = CASE fisbank "
                Sql = Sql & "                      WHEN 1 THEN '是'"
                Sql = Sql & "                      ELSE '否'"
                Sql = Sql & "                    END,"
                Sql = Sql & "          fjournal = CASE fjournal "
                Sql = Sql & "                       WHEN 1 THEN '是'"
                Sql = Sql & "                       ELSE '否'"
                Sql = Sql & "                     END,"
                Sql = Sql & "          fcontact = CASE fcontact "
                Sql = Sql & "                       WHEN 1 THEN '是'"
                Sql = Sql & "                       ELSE '否'"
                Sql = Sql & "                     END,"
                Sql = Sql & "          fiscashflow = CASE fiscashflow "
                Sql = Sql & "                          WHEN 1 THEN '是'"
                Sql = Sql & "                          ELSE '否'"
                Sql = Sql & "                        END,"
                Sql = Sql & "          fcheckcase=dbo.GetFCheckCase(fcheckcase),"
                Sql = Sql & "          fisbudget = CASE fisbudget "
                Sql = Sql & "                        WHEN 1 THEN '是'"
                Sql = Sql & "                        ELSE '否'"
                Sql = Sql & "                      END,"
                Sql = Sql & "          facctint = CASE facctint "
                Sql = Sql & "                       WHEN 1 THEN '是'"
                Sql = Sql & "                       ELSE '否'"
                Sql = Sql & "                     END,"
                Sql = Sql & "          fintrate,FFullName"
                Sql = Sql & " FROM     t_account a,"
                Sql = Sql & "          t_acctgroup b"
                Sql = Sql & " WHERE    a.fdelete = 0"
                Sql = Sql & "          AND a.fgroupid = b.fgroupid "

                If Me.txtfCode.TextLength > 0 Then
                    Sql += " and a.fnumber Like '%" & Me.txtfCode.Text.Trim & "%'"
                End If

                If Me.txtCname.TextLength > 0 Then
                    Sql += " and a.fname_cht Like '%" & Me.txtCname.Text.Trim & "%'"
                End If

                If Me.txtEname.TextLength > 0 Then
                    Sql += " and a.fname Like '%" & Me.txtEname.Text.Trim & "%'"
                End If

                Sql += "  order by FNumber"


            End If

            mDataset = ReturnDataset(Sql)
            Me.dgrdGoods.DataSource = mDataset.Tables(0)

        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        Finally
            Me.Cursor = Cursors.Default

        End Try

    End Sub


    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            If Me.dgrdGoods.SelectedRows.Count > 0 Then
                PubGoodsDataSet.Tables.Clear()

                Dim tb As New DataTable
                Dim FirstSelectRow, LastSelectRow, intSelectRows As Integer
                Dim intRows() As Integer

                '選擇的第1行

                FirstSelectRow = Me.dgrdGoods.SelectedRows(0).Index

                '選擇的最後一行

                If Me.dgrdGoods.SelectedRows.Count > 1 Then
                    LastSelectRow = Me.dgrdGoods.SelectedRows(Me.dgrdGoods.SelectedRows.Count - 1).Index

                End If


                intSelectRows = Me.dgrdGoods.SelectedRows.Count
                ReDim intRows(intSelectRows - 1)
                For i As Integer = 0 To intSelectRows - 1
                    intRows(i) = Me.dgrdGoods.SelectedRows(i).Index
                Next

                tb = mDataset.Tables(0).Copy
                tb.Rows.Clear()

                PubGoodsDataSet.Tables.Add(tb)

                '順向選擇
                If FirstSelectRow > LastSelectRow Then
                    For J As Integer = intRows.LongLength - 1 To 0 Step -1
                        'For Each row As DataGridViewRow In Me.dgrdGoods.Rows

                        Dim mRow As DataRow
                        mRow = tb.NewRow()

                        For Each col As DataColumn In tb.Columns
                            mRow(col) = Me.dgrdGoods.Rows(intRows(J)).Cells(col.ColumnName).Value
                        Next

                        tb.Rows.Add(mRow)
                        PubGoodsDataSet.AcceptChanges()

                        'Next

                    Next
                Else
                    '反向選擇
                    For J As Integer = 0 To intRows.LongLength - 1
                        'For Each row As DataGridViewRow In Me.dgrdGoods.Rows

                        Dim mRow As DataRow
                        mRow = tb.NewRow()

                        For Each col As DataColumn In tb.Columns
                            mRow(col) = Me.dgrdGoods.Rows(intRows(J)).Cells(col.ColumnName).Value
                        Next

                        tb.Rows.Add(mRow)
                        PubGoodsDataSet.AcceptChanges()

                    Next



                End If

            End If

            Me.Ds = PubGoodsDataSet


        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)

        Finally
            Me.Dispose()

        End Try

    End Sub

	Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'Me.Close()
        Me.Dispose()


    End Sub

    Private Sub dgrdGoods_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgrdGoods.CellDoubleClick
        Me.btnOK_Click(sender, e)
    End Sub

    Private Sub dgrdGoods_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgrdGoods.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                Select Case e.KeyCode
                    Case Keys.Enter
                        e.Handled = True
                        Me.btnOK_Click(sender, e)
                    Case Keys.Escape
                        Me.btnCancel_Click(sender, e)
                End Select
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub


End Class